#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h> 
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <errno.h>


#include "structure.h"
#include "toolkit.h"
#include "update.h"
#include "config.h"
#include "DEV/table_fichiers.h"


struct database db; 



int main(int argc, char *argv[]){

   
  if (argc < 2) {
    fprintf(stderr,"usage %s hostname port\n", argv[0]);
    exit(0);
  }

  db.nb_file = 0;

  TableFichiers base = init_table();
  remplir_table(PATH, &base);

 

  char buffer[MAX_LENGTH];

  bzero(buffer,MAX_LENGTH);
  write_buffer(buffer,base,atoi(argv[1]));

  args* arglist = malloc(sizeof(args));
  arglist->argv = argv;
  arglist->portno = NO_PORT_TRACKER;
  arglist->IP = IP_TRACKER;
  arglist->buffer = buffer;
  arglist->func = print;

  
  pthread_t Thread_connection;
  pthread_t Thread_listen;
  pthread_t Thread_update;

  
  if (pthread_create(&Thread_connection,NULL,(void*)send_msg,arglist) !=0)
    fprintf(stderr,"ERROR creating thread.\n");
  if (pthread_create(&Thread_listen,NULL,(void*)receive_msg,argv) !=0)
    fprintf(stderr,"ERROR creating thread.\n");
  if (pthread_join(Thread_connection, NULL) != 0)
    fprintf(stderr,"ERROR executing thread.\n");
  if (pthread_create(&Thread_update,NULL,(void*)update,NULL) !=0)
    fprintf(stderr,"ERROR creating thread.\n");
  
  int n;
  while(1){
    n = get_client_query();
    if(n == 1)
      break;
  }
  
 
  
  return 0;
}
